﻿#include "p2pchatroom.h"
#include "ui_chatroom.h"
#include <librtc.h>
#include "chatlistviewer.h"
#include "clientcallback.h"
#include "globaltools.h"

P2PChatRoom::P2PChatRoom(const P2PChanneInfo &channel_info, QWidget *parent) : ChatRoom(channel_info, parent)
{
    //判断对方是否在线
    send_msg(msg_type_ask_online, "");

    QList<QVariantHash> mic_state;

    QVariantHash mic;
    //1号麦：对方
    setParam(mic, cmd_param_mic_id, 1);
    if(channel_info.hasAudio || channel_info.hasVideo)
    {
        setParam(mic, cmd_param_uid, channel_info.id());
        if(channel_info.hasAudio)
            setParam(mic, cmd_param_audio_id, P2PChanneInfo::p2pchannel_audio_id);
        if(channel_info.hasVideo)
            setParam(mic, cmd_param_video_id, P2PChanneInfo::p2pchannel_video_id);
    }
    mic_state.append(mic);
    mic.clear();

    //2号麦：自己
    setParam(mic, cmd_param_mic_id, 2);
    mic_state.append(mic);

    handle_mic_state(mic_state, QList<QVariantHash>());
}

P2PChatRoom::~P2PChatRoom()
{
    if(acting_button)
    {
        //下麦时自动解除静音
        ui->button_micphone->setChecked(false);
        sendMediaMsg(acting_button == ui->button_camera, false);
        ClientCallback::instance()->free_p2p_channel();
    }
}

void P2PChatRoom::handle_msg(int type, const QVariantHash &msg)
{
    if(type == msg_type_dispatch_end || type == msg_type_dispatch_start)
    {
        setMicState(true, type == msg_type_dispatch_start, false);
    }
    else if(type == msg_type_notify)
    {
        QString content = getParam(msg, cmd_param_msg).toString();
        if(content == P2PChanneInfo::start_talk)
        {
            setMicState(false, true, false);
        }
        else if(content == P2PChanneInfo::end_talk)
        {
            setMicState(false, false, false);
        }
    }
    else if(type == msg_type_ask_online_ack)
    {
        //对方在线
        if(!online_list.contains(getId()))
        {
            online_list.insert(getId());
            if(auto item = ui->list_offline_user->takeItem(0))
            {
                item->setFlags(item->flags() | Qt::ItemIsEnabled);
                ui->list_online_user->addItem(item);
            }
        }
    }
    else if(type == msg_type_msg_readed)
    {
        //对方已读
         auto mids = getParam(msg, cmd_param_msg).toByteArray().split(',');
         foreach (const auto &mid, mids) {
             ui->chatWidget->getTextShow()->setMidState(mid, QObject::trECSUTF8("已读"));
         }
    }
    else if (BaseChannelInfo::isVisibleMsg(type, true))
        handle_text_msg(type, msg);
}

QByteArray P2PChatRoom::send_msg(int msg_type, const QString &text)
{
    return ClientCallback::instance()->im_send_msg(getId(), getName(ClientCallback::instance()->get_my_id()), msg_type, text);
}

void P2PChatRoom::on_button_meeting_clicked(bool checked)
{
    if(checked && acting_button == Q_NULLPTR)
    {
        acting_button = ui->button_meeting;
        setButtonStatus(-1, 1, -1);
        startSpeak();
    }
    else if(!checked && acting_button == ui->button_meeting)
    {
        acting_button = Q_NULLPTR;
        setButtonStatus(0, 0, 0);
        stopSpeak();
    }
}

void P2PChatRoom::on_button_camera_clicked(bool checked)
{
    if(checked && acting_button == Q_NULLPTR)
    {
        acting_button = ui->button_camera;
        setButtonStatus(1, -1, -1);
        setVideoEffect(true, true);

        sendMediaMsg(true, true);
        ClientCallback::instance()->create_p2p_channel(getId(), true);
        //开视频时自动静音
        ui->button_micphone->setChecked(true);

        self_speaking = true;
        ui->button_tospeak->setStyleSheet(QLatin1String("background-image: url(:/gui/mic_strength_1.png)"));
        volumeCalculated = volumeShowing = 1;

        setMicState(true, true, true);
    }
    else if(!checked && acting_button == ui->button_camera)
    {
        acting_button = Q_NULLPTR;
        setButtonStatus(0, 0, 0);
        setVideoEffect(false, true);

        //下麦时自动解除静音
        ui->button_micphone->setChecked(false);
        sendMediaMsg(true, false);
        ClientCallback::instance()->free_p2p_channel();

        self_speaking = false;
        volumeTimer.stop();
        volumeCalculated = volumeShowing = 0;
        ui->button_tospeak->setStyleSheet(QString());

        setMicState(true, false, true);
    }
}

void P2PChatRoom::on_list_online_user_customContextMenuRequested(const QPoint &pos)
{
    Q_UNUSED(pos)
}

void P2PChatRoom::startSpeak()
{
    ChatRoom::startSpeak();
    sendMediaMsg(false, true);

    ClientCallback::instance()->create_p2p_channel(getId());
    //马上处理结果
    self_speaking = true;
    ui->button_tospeak->setStyleSheet(QLatin1String("background-image: url(:/gui/mic_strength_1.png)"));
    volumeCalculated = volumeShowing = 1;

    setMicState(false, true, true);
}

void P2PChatRoom::stopSpeak()
{
    //下麦时自动解除静音
    ui->button_micphone->setChecked(false);
    sendMediaMsg(false, false);
    ClientCallback::instance()->free_p2p_channel();
    //马上处理结果
    self_speaking = false;
    volumeTimer.stop();
    volumeCalculated = volumeShowing = 0;
    ui->button_tospeak->setStyleSheet(QString());

    setMicState(false, false, true);
}

void P2PChatRoom::setMicState(bool video, bool on, bool self)
{
    auto mic_state = mic_list_.toList();
    auto &mic = mic_state[self ? 1 : 0];
    int changeParam = cmd_param_audio_id, otherParam = cmd_param_video_id;
    if(video)
    {
        changeParam = cmd_param_video_id;
        otherParam = cmd_param_audio_id;
    }
    if(getParam(mic, changeParam).toInt() > 0 == on)
        return;
    if(on)
    {
        if(getParam(mic, cmd_param_uid).toInt() <= 0)
            setParam(mic, cmd_param_uid, self ? ClientCallback::instance()->get_my_id() : getId());
        if(video)
            setParam(mic, cmd_param_video_id, P2PChanneInfo::p2pchannel_video_id);
        else
            setParam(mic, cmd_param_audio_id, P2PChanneInfo::p2pchannel_audio_id);
    }
    else
    {
        removeParam(mic, changeParam);
        if(getParam(mic, otherParam).toInt() <= 0)
            removeParam(mic, cmd_param_uid);
    }
    handle_mic_state(mic_state, QList<QVariantHash>());
}

void P2PChatRoom::sendMediaMsg(bool video, bool on)
{
    if(video)
        ClientCallback::instance()->im_send_msg(getId(), QString(), on ? msg_type_dispatch_start : msg_type_dispatch_end, QString());
    else
        ClientCallback::instance()->im_send_msg(getId(), QString(), msg_type_notify, on ? P2PChanneInfo::start_talk : P2PChanneInfo::end_talk);
}
